package com.shuiqinling.ww.android.qq;

import java.io.IOException;
import java.util.HashMap;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;

import com.shuiqinling.ww.android.AndroidDirectCall;
import com.shuiqinling.ww.android.Util.HttpUtil;
import com.shuiqinling.ww.android.Util.HttpUtil.HttpCallback;
import com.shuiqinling.ww.android.Util.UIHelper;
import com.tencent.connect.UserInfo;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

/**
 * 
 * QQ open api 的使用<br>
 * 
 * https://wiki.open.qq.com/index.php?title=Android_SDK%E5%8A%9F%E8%83%BD%E5%88%97%E8%A1%A8&oldid=47454
 * 
 * @author LSN
 *
 */
public class QQApi implements IUiListener {

	private static final String APPID = "1106442005";
	private static final String TAG = "QQLOGIN";

	private static final int REQUEST_MODE_LOGIN = 1;
	private static final int REQUEST_MODE_USERINFO = 2;

	private static QQApi instance;

	public static QQApi getInstance(Activity ctx) {
		if (instance == null) {
			instance = new QQApi(ctx);
		}
		return instance;
	}

	private Activity context;
	private Tencent mTencent;

	private int requestMode;
	private String param_openId = "";
	private String param_access_token = "";
	private String param_exprires = "";
	private String param_unionid = "";
	private String param_nickname;

	private QQApi(Activity ctx) {
		context = ctx;
		mTencent = Tencent.createInstance(APPID, ctx);
	}

	/**
	 * 
	 */
	public void doQQLogin() {
		UIHelper.ShowToast("QQ登录", 0);

		requestMode = REQUEST_MODE_LOGIN;

		if (!mTencent.isSessionValid()) {
			mTencent.login(context, "all", this);
		} else {
			// 成功
			qq_login_success();
		}
	}

	private void doGetUserInfo() {
		requestMode = REQUEST_MODE_USERINFO;
		
		if (mTencent.isSessionValid() && mTencent.getOpenId()!=null) {
			UserInfo userInfo = new UserInfo(context, mTencent.getQQToken());
			userInfo.getUserInfo(this);
		} 
		// System.out.println("doGetUserInfo:" + mTencent.getQQToken());
	}

	private void doGetUnionId() {
		final String getUnionIdRequestUrl = "https://graph.qq.com/oauth2.0/me";

		final HashMap<String, Object> requestParamsMap = new HashMap<String, Object>();
		requestParamsMap.put("access_token", param_access_token);
		requestParamsMap.put("unionid", 1);

		UIHelper.ShowToast("doGetUnionId");
		final HttpCallback httpCallback = new HttpCallback() {

			@Override
			public void OnHttpResponse(int ResponceCode, String content) {
				UIHelper.ShowToast(ResponceCode + "_" + content, 0);

				if (ResponceCode == 200) {
					try {
						JSONObject json = new JSONObject(content);
						param_unionid = json.getString("unioid");
						UIHelper.ShowToast(param_unionid, 0);
					} catch (JSONException e) {
						e.printStackTrace();
					}
				} else {
					qq_login_error(String.valueOf(ResponceCode));
				}
			}
		};

		Runnable runnable = new Runnable() {
			public void run() {
				try {
					HttpUtil.DoPost(getUnionIdRequestUrl, requestParamsMap, httpCallback);
				} catch (IOException e) {
					e.printStackTrace();
				}

			}
		};

		new Thread(runnable).start();
	}

	@Override
	public void onCancel() {
		switch (requestMode) {
		case REQUEST_MODE_LOGIN:
			UIHelper.ShowToast("用户取消QQ登录");
			HashMap<String, String> paramData = new HashMap<String, String>();
			paramData.put("status", "1");
			AndroidDirectCall.SendMessageToUnity(TAG, paramData);
			break;
		case REQUEST_MODE_USERINFO:
			break;
		default:
			break;
		}
	}

	@Override
	public void onComplete(Object arg0) {

		switch (requestMode) {
		case REQUEST_MODE_LOGIN:
			JSONObject json = (JSONObject) arg0;

			try {
				param_openId = json.getString("openid");
				param_access_token = json.getString("access_token");
				param_exprires = json.getString("expires_in");
				mTencent.setOpenId(param_openId);
				mTencent.setAccessToken(param_access_token, param_exprires);
			} catch (JSONException e) {
				e.printStackTrace();
				qq_login_error("");
			}
			// 还要获取一次 昵称
			doGetUserInfo();
			break;
		case REQUEST_MODE_USERINFO:
			if (arg0 == null) {
				return;
			}
			try {
				JSONObject jo = (JSONObject) arg0;
				int ret = jo.getInt("ret");
				param_nickname = jo.getString("nickname");
				qq_login_success();
				// doGetUnionId();
			} catch (Exception e) {
				qq_login_error("");
				e.printStackTrace();
			}
			break;

		}
	}

	@Override
	public void onError(UiError arg0) {
		qq_login_error(String.valueOf(arg0.errorCode));
	}
	
	private void qq_login_success() {
		UIHelper.ShowToast("QQ登录成功" + param_openId + "_" + param_access_token + "_" + param_exprires + "_" + param_nickname, 0);
		// 拿到昵称发送给unity
		HashMap<String, String> paramData = new HashMap<String, String>();
		paramData.put("status", "0");
		paramData.put("openid", param_openId);
		paramData.put("access_token", param_access_token);
		paramData.put("expires_in", param_exprires);
		paramData.put("nickname", param_nickname);
		AndroidDirectCall.SendMessageToUnity(TAG, paramData);
	}
	
	private void qq_login_error(String errCode) {
		UIHelper.ShowToast("QQ登录错误！");
		HashMap<String, String> paramData = new HashMap<String, String>();
		paramData.put("status", "2");
		paramData.put("errcode", errCode);
		AndroidDirectCall.SendMessageToUnity(TAG, paramData);
	}
}
